<template>
  <div class="information">
    <h2>商户基本信息</h2>
    <div v-if="merModel" class="business-msg">
      <!-- <div class="lab-title">基本信息</div> -->
      <!-- <div class="user-msg">
        <div class="basic-information">
          <div>商户名称：{{ merData.mer_name }}</div>
          <div>商户负责人手机号：{{ merData.mer_phone }}</div>
        </div>
        <div v-if="merData.merchantCategory.category_name" class="basic-information">
          <div>商户分类：{{ merData.merchantCategory.category_name || "" }}</div>
          <div>商户类别：{{ merData.is_trader ? "自营" : "非自营" }}</div>
        </div>
        <div class="basic-information">
          <div>商户负责人姓名：{{ merData.real_name }}</div>
          <div>商户入驻时间：{{ merData.create_time }}</div>
        </div>

        <div v-if="merData.sub_mchid" class="basic-information">
          <div>微信服务商ID: {{ merData.sub_mchid }}</div>
        </div>

        <div class="basic-information">
          <div>
            是否开启商户：
            <el-switch v-model="merData.mer_state" :active-value="1" :inactive-value="0" />
            <span class="trip">开启，店铺即可展示在移动端</span>
          </div>
        </div>
        <div v-if="merData.merchantType" class="basic-information">
          <div>店铺类型：{{ merData.merchantType.type_name }}</div>
        </div>
      </div> -->

      <div class="form-data">
        <el-form ref="ruleForm" :model="merData" :rules="rules" label-width="100px" class="demo-ruleForm">
          <el-form-item label="店铺头像(120*120px)" label-width="170px" prop="mer_avatar">
            <div class="upLoadPicBox" title="750*750px" @click="modalPicTap('2')">
              <div v-if="merData.mer_avatar" class="pictrue">
                <img :src="merData.mer_avatar">
              </div>
              <div v-else class="upLoad">
                <i class="el-icon-camera cameraIconfont" />
              </div>
            </div>
          </el-form-item>
          <el-form-item label="商户名称" prop="mer_name" label-width="170px">
            <div class="tip-form">
              <el-input v-model="merData.mer_name" />
            </div>
          </el-form-item>
          <el-form-item label="联系人姓名" prop="real_name" label-width="170px">
            <div class="tip-form">
              <el-input v-model="merData.real_name" />
            </div>
          </el-form-item>
          <el-form-item label="联系人电话" prop="mer_phone" label-width="170px">
            <div class="tip-form">
              <el-input v-model="merData.mer_phone" />
            </div>
          </el-form-item>
          <el-form-item label="所属菜市场" label-width="170px">
            <div class="tip-form">
              <el-input v-model="merData.market.mar_name" disabled="" />
            </div>
          </el-form-item>

          <el-form-item label="店铺Banner(710*200px)" label-width="170px" prop="mer_banner">
            <div class="upLoadPicBox" title="750*750px" @click="modalPicTap('1')">
              <div v-if="merData.mer_banner" class="pictrue">
                <img :src="merData.mer_banner">
              </div>
              <div v-else class="upLoad">
                <i class="el-icon-camera cameraIconfont" />
              </div>
            </div>
          </el-form-item>
          <!-- <el-form-item label="店铺街banner(710*134px)" label-width="170px">
            <div class="tip-form">
              <div class="upLoadPicBox" title="750*750px" @click="modalPicTap('3')">
                <div v-if="merData.mini_banner" class="pictrue">
                  <img :src="merData.mini_banner">
                </div>
                <div v-else class="upLoad">
                  <i class="el-icon-camera cameraIconfont" />
                </div>
              </div>
              <span>注:此图上传后显示在店铺街位置，如果未上传默认展示店铺Banner图</span>
            </div>
          </el-form-item> -->

          <el-form-item label="店铺资质" label-width="170px" prop="uploadedqualifications">
            <div class="upLoadPicBox_qualification">

              <div v-for="(item, index) in uploadedQualifications" :key="index" class="uploadpicBox_list">
                <div class="uploadpicBox_list_image">
                  <!-- <img :src="item.url" alt=""> -->
                  <el-image ref="elImage" :src="item.url" :preview-src-list="[item.url]" />
                </div>
                <div class="uploadpicBox_list_method">
                  <!-- deldetQualificationsList -->
                  <i class="el-icon-delete" @click="deldetQualificationsList(index)" />
                  <i class="el-icon-view" @click="viewImage(item, index)" />

                </div>
              </div>

              <el-upload :action="fileUrl" :show-file-list="false" list-type="picture-card" multiple
                :headers="myHeaders" :on-success="setQualificationsList" :before-upload="beforeUploadQualification">
                <i class="el-icon-plus"></i>
              </el-upload>
            </div>
          </el-form-item>

          <el-form-item label="商户简介" prop="mer_info" label-width="170px">
            <el-input v-model="merData.mer_info" type="textarea" placeholder="文字简介，200字以内" />
          </el-form-item>
          <el-form-item label="商户关键字" prop="mer_keyword" label-width="170px">
            <div class="tip-form">
              <el-input v-model="merData.mer_keyword" placeholder="手机/电脑/数码相机" />
              <span>设置后用户在搜索该关键字时，可搜索到本店铺</span>
            </div>
          </el-form-item>
          <el-form-item label="起送价" prop="starting_price" label-width="170px">
            <div class="tip-form">
              <el-input-number v-model="merData.starting_price" placeholder="请输入起送价,单位元" />
              <!-- <span>商户若不设置则按总后台设置的起送价为准</span> -->
            </div>
          </el-form-item>
          <el-form-item label="配送费初始值" prop="distribution_fee" label-width="170px">
            <div class="tip-form">
              <el-input-number v-model="merData.distribution_fee" placeholder="请输入配送费,单位元" />
              <span>此初始值为运费模板的初始固定距离内配送费的值</span>
            </div>
          </el-form-item>

          <el-form-item label="送达时间" prop="time_delivery" label-width="170px">
            <div class="tip-form">
              <el-input-number v-model="merData.time_delivery" placeholder="请输入送达时间,单位分钟" />
              <span>商户设置的送达时间为准</span>
            </div>
          </el-form-item>

          <el-form-item label="客服电话" prop="service_phone" label-width="170px">
            <el-input v-model="merData.service_phone" />
          </el-form-item>
          <el-form-item label="商户地址" prop="mer_address" label-width="170px">
            <el-input v-model="merData.mer_address" enter-button="查找位置" style="width: 100%"
              placeholder="请输入商户地址（地址中请包含城市名称，否则会影响搜索精度）">
              <!-- <el-button slot="append" type="primary" @click="onSearch">查找位置</el-button> -->
            </el-input>
          </el-form-item>
          <el-form-item label="商户坐标" prop="gps" label-width="170px">
            <el-row>
              <el-col :span="6">
                <el-input v-model="merData.long" placeholder="经度"></el-input>
              </el-col>
              <el-col :span="6">
                <el-input v-model="merData.lat" placeholder="纬度"></el-input>
              </el-col>
              <el-col :span="2">
                <el-button type="success" icon="el-icon-add-location" @click="pickuptype(1)" round></el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="配送范围" prop="" label-width="170px">
            <el-row>
              <el-col :span="12">
                <el-input type="textarea" v-model="coordinate_range" placeholder="范围"></el-input>
              </el-col>
              <el-col :span="2">
                <el-button type="success" icon="el-icon-add-location" @click="pickuptype(2)" round></el-button>
              </el-col>
              <el-col :span="2">
                <!-- <el-button type="danger" icon="el-icon-delete-location" round></el-button> -->
              </el-col>
            </el-row>
          </el-form-item>
          <!-- <Maps v-if="mapKey" ref="mapChild" class="map-sty" :map-key="mapKey" :lat="Number(merData.lat || 34.34127)"
            :lon="Number(merData.long || 108.93984)" :address="merData.mer_address" @getCoordinates="getCoordinates" />
          <el-form-item /> -->
          <el-form-item label="地图选择坐标" label-width="170px">
            <el-row>
              <el-col>
                <div style="width: 100%; height: 400px;">
                  <amap cache-key="coord-picker-map" mmap-style="amap://styles/whitesmoke" :center.sync="center"
                    :zoom.sync="zoom" is-hotspot @click="mapClick">
                    <!-- 卫星图 -->
                    <amap-satellite-layer :visible="satellite" />
                    <!-- 标记点 -->
                    <amap-marker v-if="position" :position.sync="position" draggable />

                    <!-- 配送范围标记 -->
                    <amap-polygon :path="merData.coordinate_range" />

                    <amap-mouse-tool :mode.sync="mode" @draw="onDraw" :clear-when-close="true" />
                  </amap>
                </div>
              </el-col>
            </el-row>

          </el-form-item>

        </el-form>
      </div>
      <div class="lab-title">功能信息</div>
      <div class="user-msg">
        <div class="basic-information">
          商户手续费：{{
            Number(merData.commission_rate) > 0
              ? parseFloat(merData.commission_rate)
              : parseFloat(merData.merchantCategory.commission_rate * 100)
          }}%
        </div>
        <div class="basic-information">
          添加商品：{{ merData.is_audit ? "需平台审核" : "平台免审核" }}
        </div>
        <div class="basic-information">
          开启直播间：{{ merData.is_bro_room ? "需平台审核" : "平台免审核" }}
        </div>
        <div class="basic-information">
          添加直播商品：{{ merData.is_bro_goods ? "需平台审核" : "平台免审核" }}
        </div>
        <div class="basic-information">
          平台首页推荐商户：{{ merData.is_best ? "是" : "否" }}
        </div>
      </div>
      <div class="submit-button">
        <el-button type="primary" :loading="submitLoading" @click="submitForm('ruleForm')">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script>
  // +----------------------------------------------------------------------
  // | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
  // +----------------------------------------------------------------------
  // | Copyright (c) 2016~2021 https://www.crmeb.com All rights reserved.
  // +----------------------------------------------------------------------
  // | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
  // +----------------------------------------------------------------------
  // | Author: CRMEB Team <admin@crmeb.com>
  // +----------------------------------------------------------------------
  import {
    storeUpdateApi,
    storeGetInfoApi,
    uploadCertificate
  } from '@/api/setting'
  import {
    getBaseInfo,
    merchantUpdate
  } from '@/api/user.js'
  import Maps from '@/components/map/map.vue'
  import {
    getToken
  } from '@/utils/auth'
  import SettingMer from '@/libs/settingMer'
  import {
    loadAmap,
    loadPlugins,
    withAmap,
  } from '@amap/amap-vue';
  export default {
    name: 'Information',
    components: {
      Maps
    },
    data() {
      var checkPhone = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入客服电话'))
        } else {
          let regPone = null
          const mobile = /^1(3|4|5|6|7|8|9)\d{9}$/ // 最新16手机正则
          const tel = /^(0[0-9]{2,3}\-)([2-9][0-9]{4,7})+(\-[0-9]{1,4})?$/ // 座机
          if (value.charAt(0) == 0) {
            // charAt查找第一个字符方法，用来判断输入的是座机还是手机号
            regPone = tel
          } else {
            regPone = mobile
          }
          if (!regPone.test(value)) {
            return callback(new Error("请填写客服电话(座机格式'区号-座机号码')"))
          }
          callback()
        }
      }
      return {
        merModel: false,
        merData: {
          coordinate_range: [], //路线  配送范围
          longitude: "", //经度
          latitude: "", //纬度
        }, // 默认数据
        myHeaders: {
          'X-Token': getToken()
        },
        uploadedQualifications: [], // 资质图片列表
        mapKey: '', // 地图key
        address: '',
        submitLoading: false, // 提交loading
        rules: {
          mer_banner: [{
            required: true,
            message: '请上传店铺banner'
          }],
          mer_avatar: [{
            required: true,
            message: '请上传店铺头像'
          }],
          mer_info: [{
              required: true,
              message: '请输入商户简介',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 200,
              message: '长度在 3 到 200 个字符',
              trigger: 'blur'
            }
          ],
          mer_keyword: [{
            required: false,
            message: '请输入商户关键字',
            trigger: 'blur'
          }],
          service_phone: [{
            required: true,
            validator: checkPhone,
            trigger: 'blur'
          }],
          mer_address: [{
            required: true,
            message: '请输入商户地址',
            trigger: 'blur'
          }],
          uploadedqualifications: [{
            required: true,
            message: '请上传商户资质',
            trigger: 'blur'
          }]
        },

        // amap
        amapSearch: "",
        gpsPickupType: null, //坐标拾取类型 1商户坐标  2 商户范围坐标
        zoom: 15, //缩放比例
        center: null,
        satellite: false, //卫星图
        position: null, //单个标记点
        mode: "none", //类型  marker 点  polyline 折现绘制
        coordinate_range: "",
      }
    },
    computed: {
      fileUrl() {
        return SettingMer.https + `/upload/certificate`
      }
    },
    watch: {
      uploadedQualifications(val) {
        // 由于 uploadedqualifications 字段未被添加到 merData 对象中，因此，使用 1 或 '' 作为符号表示 merData 中的 uploadedqualifications 图片列表是否添加完毕
        if (val.length) {
          this.merData.uploadedqualifications = 1;
        } else {
          this.merData.uploadedqualifications = '';
        }

      }
    },
    created() {
      this.getMapInfo()
      this.getInfo()
    },
    methods: {
      // 获取历史信息
      getInfo() {
        this.merModel = false
        getBaseInfo().then((res) => {
          // console.log(res.data)
          this.merData = res.data
          this.$set(this.merData, 'uploadedqualifications', '') // 资质图片列表
          this.merModel = true
          if (res.data.mer_certificate instanceof Array) {
            res.data.mer_certificate.forEach((item) => {
              this.uploadedQualifications.push({
                url: item
              })
            })
          } else {
            this.uploadedQualifications = []
          }

          if (this.merData.coordinate_range) {
            this.coordinate_range = this.merData.coordinate_range
            this.merData.coordinate_range = JSON.parse(this.merData.coordinate_range)
          } else {
            this.merData.coordinate_range = []
            this.coordinate_range = ""
          }
          if (Number(this.merData.lat)) {
            this.position = [this.merData.long, this.merData.lat]
          } else {
            this.position = null
            this.merData.lat = ""
            this.merData.long = ""
          }
        })
      },
      // 提交/修改
      submitForm(formName) {
        this.$refs[formName].validate(valid => {
          if (valid) {
            const dataKey = Object.keys(this.rules)
            const reqData = {};
            [...dataKey, 'mer_state','time_delivery', 'long', 'lat', 'mini_banner', 'coordinate_range','distribution_fee','starting_price'].map(item => {
              reqData[item] = this.merData[item]
            })
            console.log(reqData);
            reqData.mer_certificate = this.uploadedQualifications.map(item => item.response ? item.response.data
              .src : item.url)
            this.submitLoading = true
            merchantUpdate(reqData)
              .then((res) => {
                console.log(res)
                this.submitLoading = false
                this.$message.success('提交成功')
              })
              .catch((rej) => {
                this.submitLoading = false
                this.$message.error(rej.data.message)
              })
          } else {
            this.$message.error('请完善信息后再进行提交')
            this.submitLoading = false
            return false
          }
        })
      },
      // 查找位置
      onSearch() {
        // console.log(this.$refs)
        this.$refs.mapChild.searchKeyword(this.merData.mer_address)
      },
      // 获取 map key
      getMapInfo() {
        const that = this
        storeGetInfoApi()
          .then((res) => {
            console.log(res)
            this.mapKey = res.data.tx_map_key
          })
          .catch(function(res) {
            that.$message.error(res.message)
          })
      },
      // 上传图片
      modalPicTap(tit, num, i) {
        const _this = this
        const attr = []
        this.$modalUpload((img) => {
          if (tit === '1' && !num) {
            _this.merData.mer_banner = img[0]
          }
          if (tit === '2' && !num) {
            _this.merData.mer_avatar = img[0]
          }
          if (tit === '3' && !num) {
            _this.merData.mini_banner = img[0]
          }
        }, tit)
      },

      // 资质图片删除
      deldetQualificationsList(index) {
        this.uploadedQualifications.splice(index, 1)
      },
      // 上传文件之前的钩子函数
      beforeUploadQualification() {
        if (this.uploadedQualifications.length >= 5) {
          this.$message.error('上传文件最大数量为5张, 上传失败!');
          return false;
        } else {
          return true;
        }
      },
      // 上传成功
      setQualificationsList(response) {
        if (response.status === 200) {
          this.uploadedQualifications.push({
            url: response.data.src
          })
          // this.$message.success("上传成功");
        } else {
          this.$message.error(response.message)
        }
      },
      // 查看资质图片
      viewImage(item, index) {
        this.$refs.elImage[index].clickHandler()
      },
      // map
      mapClick(e) { //地图点击事件
        if (!this.gpsPickupType) {
          // this.$message.error("请选择拾取gps坐标类型")
          this.position = null
          return false;
        }
        if (e.lnglat) {
          this.position = [e.lnglat.lng, e.lnglat.lat];
          if (this.gpsPickupType == 1) {
            this.merData.lat = e.lnglat.lat
            this.merData.long = e.lnglat.lng
          } else {
            // let arr = [e.lnglat.lng, e.lnglat.lat]
            // this.$set(this.coordinate_range, this.coordinate_range.length, arr)
          }

        } else {
          this.position = null;
        }
      },
      pickuptype(type) {
        this.gpsPickupType = type
        if (type == 1) {
          this.mode = "marker"
        } else if (type == 2) {
          this.mode = "polyline"
        } else {
          this.mode = "none"
        }
      },
      onDraw(type, obj) {
        const json = JSON.stringify({
          type,
          obj
        }, null, '  ');
        this.gpsPickupType = null

        // console.log(type)
        // console.log(obj)
        this.$message.info("gps坐标拾取成功");
        if (type === "polyline") {
          this.merData.coordinate_range = obj
          this.coordinate_range = JSON.stringify(obj)
          // this.$set(this.editData.coordinate_range,0)
        }

      }


    },
  }
</script>

<style lang="scss" scoped>
  .information {
    width: 100%;
    padding: 30px 40px 80px 40px;
    display: flex;
    flex-direction: column;
    align-items: center;

    .business-msg {
      width: 80%;
    }

    h2 {
      text-align: center;
      color: #ffffff;
      background-color: #4784ff;
      padding: 10px 40px;
      border-radius: 25px 0 25px 0;
    }

    .lab-title {
      width: max-content;

      font-size: 18px;
      font-weight: bold;
      color: #ffffff;
      background-color: #4784ff;
      // border-bottom: 2px solid #ccc;
      margin: 10px 10%;
      padding: 10px 20px;
      border-radius: 25px 0 25px 0;
    }

    .user-msg {
      padding: 0 20px;
    }

    .basic-information {
      display: flex;
      justify-content: space-between;
      padding: 10px 10%;
      font-size: 13px;
      font-weight: bold;
      text-rendering: optimizeLegibility;
      font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB,
        Microsoft YaHei, Arial, sans-serif;
      color: #606266;

      >div {
        width: 350px;
        flex-wrap: nowrap;
        display: flex;
        align-items: center;
        flex-wrap: nowrap;
        white-space: nowrap;

        .trip {
          padding-left: 10px;
          color: #e72222;
        }
      }
    }

    .form-data {
      padding: 30px 10%;

      .map-sty {
        width: 90%;
        text-align: right;
        margin: 0 0 0 10%;
      }

      .pictrue img {
        border-radius: 4px;
        object-fit: cover;
      }

      .tip-form {
        display: flex;
        align-items: center;

        span {
          white-space: nowrap;
          padding-left: 10px;
          color: rgb(168, 159, 159);
        }
      }
    }

    .submit-button {
      display: flex;
      justify-content: center;
      position: fixed;
      bottom: 20px;
      // left: 50%;
      width: 80%;
      padding: 10px 0;
      background-color: rgba(255, 255, 255, 0.7);
    }
  }

  /deep/ .el-upload--picture-card {
    width: 58px;
    height: 58px;
    line-height: 70px;
  }

  /deep/.el-upload-list__item {
    width: 58px;
    height: 58px;
  }

  .upLoadPicBox_qualification {
    display: flex;
    flex-wrap: wrap;

    .uploadpicBox_list {
      position: relative;
      height: 58px;
      width: 58px;
      margin: 0 20px 20px 0;

      .uploadpicBox_list_image {
        position: absolute;
        top: 0;
        left: 0;
        width: 58px;
        height: 58px;
        border-radius: 4px;
        overflow: hidden;

        img {
          width: 100%;
          height: 100%;
        }
      }

      .uploadpicBox_list_method {
        position: absolute;
        top: 0;
        left: 0;
        font-size: 18px;
        font-weight: bold;
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: space-around;
        background: rgba(0, 0, 0, 0.4);
        border-radius: 4px;
        opacity: 0;
        width: 100%;
        height: 100%;
        transition: 0.3s;
      }
    }
  }

  .uploadpicBox_list:hover .uploadpicBox_list_method {
    z-index: 11;
    opacity: 1;
  }
</style>
